package com.yumeno.education.controller;

import com.yumeno.education.entity.AjaxRespInfo;
import com.yumeno.education.entity.Questions;
import com.yumeno.education.entity.Student;
import com.yumeno.education.service.StudentService;
import com.yumeno.education.service.impl.QuestionsServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Resource
    private StudentService studentService;

    @Resource
    private QuestionsServiceImpl questionsService;

    @RequestMapping("/loginPage")
    public ModelAndView loginPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("student/login");
        return modelAndView;
    }

    @RequestMapping("/studentIndex")
    public ModelAndView studentIndex() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("student/studentIndex");
        return modelAndView;
    }

    @RequestMapping("/questionPage")
    public ModelAndView questionPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("student/questionPage");
        return modelAndView;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "index";
    }

    @RequestMapping("/getQuestions")
    @ResponseBody
    public AjaxRespInfo<Questions> getQuestions() {
        AjaxRespInfo<Questions> ajaxRespInfo = new AjaxRespInfo<>();
        Questions dbQuestions = questionsService.getQuestions();
        if (dbQuestions != null) {
            ajaxRespInfo.setData(dbQuestions);
        } else {
            ajaxRespInfo.setCode(-1);
            ajaxRespInfo.setMsg("你完成了所有问题！");
        }
        return ajaxRespInfo;
    }

    @RequestMapping("/login")
    ModelAndView login(Student student) {
        ModelAndView mv = new ModelAndView();
        if (StringUtils.isEmpty(student.getUsername()) || StringUtils.isEmpty(student.getPassword())) {
            mv.addObject("errMsg", "用户名或密码为空！");
            mv.setViewName("/student/login");
        }else{
            Student dbStudent = studentService.login(student);
            if (dbStudent != null) {
                mv.addObject("student", dbStudent);
                mv.setViewName("student/studentIndex");
            } else {
                mv.addObject("errMsg", "账号或密码错误！");
                mv.setViewName("/student/login");
            }
        }
        return mv;
    }

}
